<template>
    <div class="Nav font pt-10 pb-5">
        <nav class="nav flex aic jc-sb">
            <div class="left flex aic ml-10">
                <div class="flex aic mr-21">
                    <p @click="more" class="cp"
                        :class="{ 'iconfont icon-gengduo': store.state, 'iconfont icon-gengduo1': !store.state }"></p>
                    <el-input v-model="input2" @input="(val) => { pubSearch(val) }" @clear="clearSear" clearable
                        class="w-50 ml-20" placeholder="Search" :prefix-icon="Search" />
                </div>
                <!-- 标签 -->
                <div class="ml-10 flex aic">
                    <div class="tab flex aic jc-c" :class="{ active: item.name == router.currentRoute.value.path }"
                        v-for="item in tabArr" :key="item.label" @contextmenu.prevent="rightClick">
                        <router-link class="tabList" :class="{ 'pl-10': tabArr.length != 1 }" active-class="active1"
                            :to="item.name">
                            {{ item.label }}
                        </router-link>
                        <transition name="el-fade-in-linear">
                            <i v-if="tabArr.length != 1" @click="tabDel(item.name)" class="tabDel iconfont icon-dacha"></i>
                        </transition>
                    </div>
                </div>
            </div>
            <div class="right flex aic">
                <el-badge :value="12" :max="99">
                    <i class="iconfont icon-mn_pengyou"></i>
                </el-badge>
                <el-badge :value="100" :max="99">
                    <i class="iconfont icon-xitongxiaoxi"></i>
                </el-badge>
                <!-- 语言切换 -->
                <el-dropdown>
                    <i class="iconfont"
                        :class="{ 'icon-zhongyingwen2zhongwen': locale == 'zh-cn', 'icon-a-zhongyingwenyingwen': locale == 'en-us' }"
                        style="font-size: 24px;"></i>
                    <template #dropdown>
                        <el-dropdown-menu style="width: 80px;">
                            <el-dropdown-item @click="language('zh-cn')">中文</el-dropdown-item>
                            <el-dropdown-item @click="language('en-us')">English</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <!-- 登录 -->
                <div v-if="store.token" class="flex aic">
                    <el-dropdown>
                        <img class="icon" src="../../assets/img/tx.jpg" />
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="secede">退出</el-dropdown-item>
                                <el-dropdown-item>设置</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <div class="ml-10 f12">
                        <p>{{ store.UserGroupName }}</p>
                        <p>{{ store.usemame }}</p>
                    </div>
                </div>
                <div v-else class="flex aic f14">
                    <p class="cp" @click="dialog = true">登 录</p>
                    <p class="cp ml-20" @click="enrollDialog = true">注 册</p>
                </div>
            </div>
        </nav>
        <!-- 登录弹窗 -->
        <el-dialog v-model="dialog" @opened="loginDialog" :title="store.type == '4' ? 'Bind the user' : 'login'" width="25%"
            center :close-on-press-escape="false" :show-close="false" :close-on-click-modal="false">
            <el-input v-model="usemame" ref="refUsemame" @keyup.enter="enter" placeholder="usemame"></el-input>
            <el-input v-model="password" @keyup.enter="enter" class="mt-5" type="password" show-password
                placeholder="password"></el-input>
            <template #footer>
                <div class="flex aic jc-c">
                    <span class="w25p"></span>
                    <span class="dialog-footer">
                        <el-button @click="cancel">Cancel</el-button>
                        <el-button type="primary" @click="login">
                            Confirm
                        </el-button>
                    </span>
                    <span class="w25p cp f10 flex jc-e blue" @click="butEnroll">Register Now</span>
                </div>
            </template>
        </el-dialog>

        <!-- 注册 -->
        <el-dialog v-model="enrollDialog" title="Welcome to register" width="35%" center>
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="left" label-width="82px"
                hide-required-asterisk class="demo-ruleForm" status-icon>
                <el-form-item label="Name:" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="Please enter user name" />
                </el-form-item>
                <el-form-item label="Phone:" prop="phone">
                    <el-input v-model="ruleForm.phone" placeholder="Please enter a phone number" />
                </el-form-item>
                <el-form-item label="Postbox:" prop="postbox">
                    <el-input v-model="ruleForm.postbox" placeholder="Please enter email" />
                </el-form-item>
                <el-form-item label="Sex:" prop="sex">
                    <el-select v-model="ruleForm.sex" placeholder="Activity zone">
                        <el-option label="man" value="1" />
                        <el-option label="woman" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="Password:" prop="password">
                    <el-input v-model="ruleForm.password" placeholder="Please input a password" type="password"
                        show-password />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="flex aic jc-c">
                    <span class="w30p"></span>
                    <span class="dialog-footer">
                        <el-button @click="enrollDialog = false">Cancel</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            Login
                        </el-button>
                    </span>
                    <p class="w30p f14 flex aic jc-e fa5">Existing account?<span @click="account"
                            class="cp blue ml-5">login</span></p>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { menusEvent } from 'vue3-menus';  //鼠标右键功能菜单
import { ElMessage } from 'element-plus'
import { useDemoStore } from '../../pinia/index'
import * as $axios from '../../api/index'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n' //国际化
const { locale } = useI18n();
const router = useRouter()
const store = useDemoStore()

// 搜索输入框
const input2 = ref('')

// 展开(关闭)侧边栏
const more = () => {
    store.changeState(!store.state);
}
// 登录对话框
const dialog = ref(false)

defineExpose({
    dialog
})

// 注册对话框
const enrollDialog = ref(false)
const butEnroll = () => {
    dialog.value = false
    enrollDialog.value = true
}

// 切换语言
const language = (val) => {
    locale.value = val
    store.changeLang(val)
    const data = {
        token: store.token,
        lang: val
    }
    $axios.$userSet_lang(data).then(res => {
        // location.reload(); //重新加载页面
        console.log(res)
    })
}

// 账号密码
const usemame = ref('')
const password = ref('')

// 回车触发
const enter = () => {
    login()
}

// 取消登录
const cancel = () => {
    dialog.value = false
}

// 登录对话框
const refUsemame = ref()
const loginDialog = () => {
    refUsemame.value.focus() //获取账号输入框焦点
}

// 登录
const login = () => {
    const data = {
        username: usemame.value,
        pwd: password.value
    }
    $axios.$login(data).then((res) => {
        console.log(res.data)
        if (res.Status == 0) {
            dialog.value = false
            ElMessage({
                message: 'Login Success',
                type: 'success',
            })
            setTimeout(() => {
                location.reload(); //重新加载页面
            }, 1000)
            store.changeToken(res.data.token);
            store.changeType(res.data.type)
            store.changeUsemame(res.data.user_mail)
            store.changeName(res.data.nickname);
            store.changeLang(res.data.lang)
            store.changeUser(res.data.user_info.id)

        }
    })
}

// 退出登录
const secede = () => {
    location.reload(); //重新加载页面
    store.changeToken('')
    store.changeType('')
    store.changeName('')
    cookie.value = ''
}


// 注册
const ruleFormRef = ref()
const ruleForm = ref({
    name: '',
    phone: '',
    postbox: '',
    sex: '1',
    password: ''
})


// 表单验证规则
const rules = ref({
    name: [
        { required: true, message: 'Please enter user name', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: 'Please enter your mobile number', trigger: 'blur' },
        // { pattern:/^1[34578]\d{9}$/, message: 'Invalid mobile number', trigger: 'change' }
    ],
    postbox: [
        { required: true, message: 'Please enter the mailbox number', trigger: 'blur' },
        { type: 'email', message: 'Please input correct email address', trigger: ['change', 'blur'] }
    ],
    password: [
        { required: true, message: 'Please input a password', trigger: 'blur' },
        { min: 6, max: 15, message: 'Please enter a password of 6 to 15 digits', trigger: ['change', 'blur'] }
    ]
})

// 注册按钮
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const data = {
                nickname: ruleForm.value.name,
                user_mail: ruleForm.value.postbox,
                phone: ruleForm.value.phone,
                user_psw: ruleForm.value.password,
                user_sex: ruleForm.value.sex
            }
            $axios.$registerRegister(data).then(res => {
                if (res.Status == 0) {
                    store.changeToken(res.data.token);
                    store.changeType(res.data.type)
                    store.changeUser(res.data.user_info.id)
                    store.changeUsemame(ruleForm.value.postbox)
                    store.changeName(ruleForm.value.name);
                    enrollDialog.value = false
                    ElMessage({
                        message: 'Login Success',
                        type: 'success',
                    })
                    setTimeout(() => {
                        location.reload(); //重新加载页面
                    }, 1000)
                }
                // console.log(res.data)
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 已有账号
const account = () => {
    dialog.value = true
    enrollDialog.value = false
}

//  监听窗口关闭 
let _beforeUnload_time = '';
let _gap_time = '';

let beforeunloadHandler = (e) => {
    _beforeUnload_time = new Date().getTime();
};

let unloadHandler = (e) => {
    _gap_time = new Date().getTime() - _beforeUnload_time;
    //判断是窗口关闭还是刷新
    if (_gap_time <= 5) { //窗口关闭清空store
        if (store.type == 4) {
            store.changeToken('')
            store.changeType('')
            store.changeName('')
            store.changeUsemame('')
            store.changeTab('')
            store.changeState(false)
            store.changeLang('en-us')
        }
        store.changeReadStore(true)
    }
}

// 读取cookie，看有没有token
const cookieList = ref(document.cookie.split(';'))
const token = ref('')
cookieList.value.forEach(item => {
    const tokenArr = cookieList.value[item.indexOf('token=')]
    if (tokenArr == undefined) return
    token.value = tokenArr.split('token=')[1]
})
const readToken = () => {
    if (token.value) {
        const data = {
            bindToken: token.value
        }
        $axios.$userNoUserLogin(data).then(res => {
            console.log(res.data)
            if (res.Status == 0) {
                store.changeToken(res.data.token);
                store.changeType(res.data.type)
                store.changeUsemame(res.data.user_mail)
                store.changeName(res.data.nickname);
                store.changeLang(res.data.lang)
            }
        })
    }
}

const currentRoute = ref('')
// 搜索方法
const pubSearch = (val) => {
    if (currentRoute.value === '/order') {
        emits('searchOrderList', val)
    }
}
const emits = defineEmits(['searchOrderList'])

onMounted(() => {
    // window.addEventListener('beforeunload', e => beforeunloadHandler(e))
    // window.addEventListener("unload", (e) => unloadHandler(e));
    currentRoute.value = router.currentRoute.value.path
    locale.value = store.lang
    readToken()
})



// 标签列表
const editableTabs = ref([{
    name: router.currentRoute.value.path,
    label: router.currentRoute.value.path.split('/')[1]
}])
// 合并数组
const tabArrs = ref([
    ...store.tabList,
    ...editableTabs.value
])

// 去重
const tabArr = ref([])
tabArrs.value.forEach(item => {
    if (!tabArr.value.some(arr => arr.label == item.label)) {
        tabArr.value.push(item)
    }
})
store.changeTab(tabArr.value)
// console.log(tabArr.value)


// 删除触发
const tabDel = (value) => {
    const index = tabArr.value.findIndex(item => item.name == value)
    if (router.currentRoute.value.path == value) { //判断是否是当前选中的值
        if (tabArr.value[index - 1] == undefined) {
            router.push(tabArr.value[index + 1].name)
        } else if (tabArr.value[index + 1] == undefined) {
            router.push(tabArr.value[index - 1].name)
        } else {
            router.push(tabArr.value[index + 1].name)
        }
    }
    tabArr.value.splice(index, 1)
    // console.log(tabArr.value)
}


// 右键菜单
const rightClick = (event) => {
    menusEvent(event, menus.value);
    event.preventDefault();
}
const menus = ref({
    menus: [
        {
            label: "关闭其他",
            // icon: '<i class="iconfont icon-24gl-folderPlus"></i>',
            // tip: '',
            click: () => {
                closeAll()
            }
        },
        {
            label: "关闭到右侧",
            // icon: '<i class="iconfont icon-xiazai"></i>',
            // tip: ' ',
            click: () => {
                closeToRight()
            }
        },
    ]
});

// 关闭其他
const closeAll = () => {
    tabArr.value.forEach(item => {
        if (item.name != router.currentRoute.value.path) {
            tabArr.value.length = 0
            tabArr.value.push({
                name: router.currentRoute.value.path,
                label: router.currentRoute.value.path.split('/')[1]
            })
        }
    })

}
// 关闭到右侧
const closeToRight = () => {
    const index = tabArr.value.findIndex(item => item.name == router.currentRoute.value.path)
    tabArr.value.splice(index + 1, 15)
    // console.log(index)
}

</script>

<style lang="less" scoped>
.Nav {
    // border: 1px solid red;
    height: 55px;

    .el-tabs {
        height: 30px;
        --el-tabs-header-height: 2;
        // border: 1px solid red;
    }


    .nav {
        width: 100%;
        background-color: #f1f1f1;

        .iconfont {
            font-size: 25px;
        }

        .el-input {
            width: 100%;
        }

        .left {
            .tab {
                margin-left: 1px;
                min-width: 80px;
                transition: all 0.1s ease-in;

                .tabList {
                    // width: 90px;
                    line-height: 1.6;
                    text-align: center;
                    // display: block;
                    color: #ADADAD;
                }

                .tabDel {
                    font-size: 13px !important;
                    font-weight: 900;
                    // right: 10px;
                    visibility: hidden;
                    cursor: pointer;
                    color: #747474;
                    transition: all 0.1s ease-in;
                }
            }

            .active {
                background-color: #dddddd;
                border-radius: 5px 5px 0 0;
                color: #747474;
                border-bottom: 2px solid #747474;
            }

            .active .tabList {
                color: #747474;
            }

            .tab:hover {
                background-color: #dddddd;
                border-radius: 5px 5px 0 0;
                color: #747474;
                border-bottom: 2px solid #747474;
                transition: all 0.1s ease-in;
            }

            .tab:hover .tabList {
                transition: all 0.1s ease-in;
                color: #747474;
            }

            .tab:hover .tabDel {
                visibility: visible;
                padding-left: 10px;
                padding-right: 5px;
                transition: all 0.15s ease-in;
            }
        }

        .right {
            width: 25%;
            height: 100%;
            justify-content: space-around;

            .icon {
                width: 40px;
                height: 40px;
                border-radius: 50%;
            }
        }

    }

    .masked {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: 0 auto;
        z-index: 19;
        background-color: #000000a8;

        .login {
            margin: 0 auto;
            padding: 10px;
            margin-top: 13%;
            width: 22%;
            height: 240px;
            background-image: url('../../assets/img/login.jpg');
            background-size: contain;
            border-radius: 7px;

            .inp {
                border: none;
                background-color: #ffffff00;
                outline: none;
                border-bottom: 1px solid #fff;
                width: 80%;
                font-size: 16px;
                line-height: 2;
                color: rgb(255, 255, 255);
                padding: 0 5px;

            }
        }
    }
}
</style>